export const judgeSys = () => {
  const ua = navigator.userAgent
  const android = ua.match(/(Android);?[\s\/]+([\d.]+)?/)
  const iphone = ua.match(/(iPhone\sOS)\s([\d_]+)/)
  const ipad = ua.match(/(iPad).*OS\s([\d_]+)/)
  const mac = ua.match(/macintosh|mac os x/i)
  if (android) {
    return 'android'
  } else if (iphone || ipad || mac) {
    return 'ios'
  }
}

/**
     * @param {nativeFuncName}  方法名
     * @param {params}  向native传参数
     */
export const nativeHandler = (nativeFuncName = '', params = {}) => {
  let promise
  switch (judgeSys()) {
    case 'android':
      promise = new Promise((resolve, reject) => {
        window.MAPTBridge.send(nativeFuncName, params, function(response) {
          const {
            success,
            data,
            error
          } = response
          if (success === 1) {
            resolve(data)
          } else {
            reject(error)
          }
        })
      })
      break
    case 'ios':
      promise = new Promise((resolve, reject) => {
        const callBack = (bridge) => {
          bridge.callHandler(nativeFuncName, params, function(response) {
            const {
              success,
              data,
              error
            } = response
            if (success === 1) {
              resolve(data)
            } else {
              reject(error)
            }
          })
        }
        const bridgeHandler = (callback) => {
          if (window.WKWebViewJavascriptBridge) { return callback(window.WKWebViewJavascriptBridge) }
          if (window.WKWVJBCallbacks) {
            return window.WKWVJBCallbacks.push(callback)
          }
          window.WKWVJBCallbacks = [callback]
          window.webkit.messageHandlers.iOS_Native_InjectJavascript.postMessage(null)
        }
        bridgeHandler(callBack)
      })
      break
    default:
      promise = new Promise((resolve, reject) => {
        const erroMsg = '环境出错,当前环境是web环境'
        reject(erroMsg)
      }).catch(res => {
        res = this.erroMsg
        console.log(res)
      })
      break
  }
  return promise
}

export default {
  install(Vue) {
    Object.defineProperty(Vue.prototype, '$judgeSys', { value: judgeSys })
    Object.defineProperty(Vue.prototype, '$isIos', { value: judgeSys() === 'ios' })
    Object.defineProperty(Vue.prototype, '$isAndroid', { value: judgeSys() === 'android' })
    Object.defineProperty(Vue.prototype, '$nativeHandler', { value: nativeHandler })
  }
}

